import React, { PureComponent } from 'react';
import { Card, Button, Row, Col, Select, Checkbox, DatePicker } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import router from 'umi/router';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import ProjectsPath from '@/components/ProjectsPath';
import CurrentStage from '../../components/CurrentStage';
import PageEmpty from '@/components/PageEmpty';
import AuthorizedButton from '@/components/AuthorizedButton';
import styles from '../../index.less';
import qs from 'qs';
import { utils, BaseTable, TextWithTags, NumberView } from '@/components/BaseTable';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';

@connect(state => ({
  items: state.PriceManageEntireProjectItems,
  orgStructure: state.orgStructure,
}))
export default class EntireProject extends PureComponent {
  state = {
    emptyTitle: '全盘货值数据请求中...',
    yearMonth: moment().format('YYYY-MM'),
    attributesCheckeds: ['num', 'area', 'aver', 'price'],
    oldVersionOptionsCheckeds: ['num', 'area', 'aver', 'price'],
    attributes: [
      { label: '套数', value: 'num' },
      { label: '面积', value: 'area' },
      { label: '均价', value: 'aver' },
      { label: '金额', value: 'price' },
    ],
    titleTree: [
      {
        name: '项目/分期/组团/产品/楼栋',
        key: 'id',
        colspan: 1,
        rowspan: 4,
        show: true,
      },
      {
        name: '最新全盘动态货值',
        key: 'newestAllDynamic',
        rowspan: 1,
        show: true,
        children: [
          {
            name: '总货值(不含未推售车位)',
            key: 'dynamic_total_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '已售货值(不含未推售车位)',
            key: 'dynamic_sale_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '存货货值(不含未推售车位)',
            key: 'dynamic_stock_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '规划货值(不含未推售车位)',
            key: 'dynamic_plan_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '权益货值',
            key: 'dynamic_right_price',
            colspan: 1,
            attributes: ['price'],
            edit: false,
          },
          {
            name: '未推售车位货值',
            key: 'dynamic_un_send_price',
            colspan: 1 * 2,
            attributes: ['num', 'price'],
            edit: false,
          },
        ],
      },
      {
        name: (
          <>
            <div>土储货值</div>
            <div>投资口径</div>
          </>
        ),
        key: 'land_invest_price',
        rowspan: 2,
        colspan: 1 * 4,
        attributes: ['num', 'area', 'aver', 'price'],
        edit: true,
        show: true,
      },
      {
        name: (
          <>
            <div>土储货值</div>
            <div>香港口径</div>
          </>
        ),
        key: 'land_hk_price',
        rowspan: 2,
        colspan: 1 * 4,
        attributes: ['num', 'area', 'aver', 'price'],
        edit: true,
        show: true,
      },
      {
        name: '未开工货值',
        key: 'un_start_price',
        rowspan: 2,
        colspan: 1 * 4,
        attributes: ['num', 'area', 'aver', 'price'],
        edit: true,
        show: true,
      },
      {
        name: '在途货值',
        key: 'zthz',
        rowspan: 1,
        edit: false,
        show: true,
        children: [
          {
            name: '已开工未达形象进度',
            key: 'un_reach_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '已达形象进度未取证',
            key: 'un_get_card_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '在途货值合计',
            key: 'on_way_price',
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
        ],
      },
      {
        name: '库存货值构成',
        key: 'store',
        rowspan: 1,
        edit: false,
        show: true,
        children: [
          {
            name: '90天以内',
            key: 'stock_90_price',
            rowspan: 1,
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '90 ~ 180天',
            key: 'stock_90_180_price',
            rowspan: 1,
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '180 ~ 360天',
            key: 'stock_180_360_price',
            rowspan: 1,
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '360 ~ 720天',
            key: 'stock_360_720_price',
            rowspan: 1,
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '滞重库存 (720天以上)',
            key: 'stock_720_price',
            rowspan: 1,
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
          {
            name: '现房库存',
            key: 'stock_exist_room_price',
            rowspan: 1,
            colspan: 1 * 4,
            attributes: ['num', 'area', 'aver', 'price'],
            edit: true,
          },
        ],
      },
    ],
  };

  // 初始化
  async componentDidMount() {
    this.getItems(this.props);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.match.params.project !== nextProps.match.params.project) {
      this.getItems(nextProps, this.state.yearMonth);
    }
  }

  // 显示套数-面积-均价-金额
  onChangeAttributesCheckeds = checkedValues => {
    const { titleTree, oldVersionOptionsCheckeds } = this.state;
    const newTitleTree = utils.changeTreeBaseSpan(
      titleTree,
      _.difference(oldVersionOptionsCheckeds, checkedValues),
    );
    newTitleTree[0].colspan = 1;
    this.setState({
      attributesCheckeds: checkedValues,
      titleTree: newTitleTree,
    });
  };

  getItems = (props, endDate = moment().format('YYYY-MM')) => {
    const self = this;
    this.setState({ emptyTitle: '全盘货值数据加载中...' });
    const { dispatch, match } = props;
    const params = {
      endDate,
      orgId: match.params.project,
    };
    dispatch({
      type: 'PriceManageEntireProjectItems/init',
      payload: { params },
      callback: data => {
        if (data.length <= 0) {
          self.setState({ emptyTitle: '暂无全盘货值数据' });
        }
      },
    });
  };

  publicFun = (item, attributesCheckeds, fixedColumns) => {
    // 套数/车位数
    if (_.includes(attributesCheckeds, 'num')) {
      fixedColumns.push({
        key: `${item.key}roomCount`,
        dataKey: `${item.key}roomCount`,
        title: '',
        align: 'right',
        width: attributesCheckeds.length === 1 ? 160 : 110,
        dataGetter: ({ rowData }) => {
          let number = [];
          if (!rowData[item.key] || _.isEmpty(rowData[item.key])) {
            return '';
          }
          const rowDataX = rowData[item.key];
          if (
            rowData.orgType === 'org_project' ||
            rowData.orgType === 'org_stage' ||
            rowData.orgType === 'org_group'
          ) {
            if (_.isNumber(rowDataX.roomCount)) {
              number.push(rowDataX.roomCount);
            }
            if (_.isNumber(rowDataX.carPlateCount)) {
              number.push(rowDataX.carPlateCount);
            }
          } else if (
            (rowData.orgType === 'org_build' ||
              rowData.orgType === 'org_product' ||
              rowData.orgType === 'org_house_package') &&
            !rowDataX.isParking
          ) {
            number = rowDataX.roomCount;
          } else if (rowDataX.isParking) {
            number = rowDataX.carPlateCount;
          }

          return utils.calculate.NumberView({
            cellData: number,
            precision: 0,
          });
        },
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} type={1}>
              <div>套数/车位数 </div>
              <div>(套/个)</div>
            </HeaderRenderer>
          </div>
        ),
      });
    }
    // 面积
    if (_.includes(attributesCheckeds, 'area')) {
      fixedColumns.push({
        key: `${item.key}area`,
        dataKey: `${item.key}area`,
        title: '',
        align: 'right',
        width: attributesCheckeds.length === 1 ? 160 : 100,
        headerRenderer: () => (
          <div>
            <div>面积</div>
            <div>(平米)</div>
          </div>
        ),
        dataGetter: ({ rowData }) => {
          if (rowData[item.key].isParking) return '';
          if (rowData[item.key] && _.isNumber(rowData[item.key].area)) {
            return [rowData[item.key].area];
          }
          return '';
        },
        cellRenderer: <NumberView precision={2} />,
      });
    }
    // 均价
    if (_.includes(attributesCheckeds, 'aver')) {
      fixedColumns.push({
        key: `${item.key}averagePrice`,
        dataKey: `${item.key}averagePrice`,
        title: '',
        align: 'right',
        width: attributesCheckeds.length === 1 ? 160 : 130,
        dataGetter: ({ rowData }) => {
          if (!rowData[item.key] || _.isEmpty(rowData[item.key])) {
            return '';
          }
          const rowDataX = rowData[item.key];
          let number = [];
          if (
            rowData.orgType === 'org_project' ||
            rowData.orgType === 'org_stage' ||
            rowData.orgType === 'org_group'
          ) {
            if (rowDataX.roomTotalPrice <= 0 || rowDataX.area <= 0) {
              number.push(0);
            } else {
              number.push(rowDataX.roomTotalPrice / rowDataX.area);
            }
            if (rowDataX.carPlateTotalPrice <= 0 || rowDataX.carPlateCount <= 0) {
              number.push(0);
            } else {
              number.push(rowDataX.carPlateTotalPrice / rowDataX.carPlateCount);
            }
          } else if (
            (rowData.orgType === 'org_build' ||
              rowData.orgType === 'org_product' ||
              rowData.orgType === 'org_house_package') &&
            !rowDataX.isParking
          ) {
            if (rowDataX.roomTotalPrice <= 0 || rowDataX.area <= 0) {
              number = 0;
            } else {
              number = rowDataX.roomTotalPrice / rowDataX.area;
            }
          } else if (rowDataX.isParking) {
            if (rowDataX.carPlateTotalPrice <= 0 || rowDataX.carPlateCount <= 0) {
              number = 0;
            } else {
              number = rowDataX.carPlateTotalPrice / rowDataX.carPlateCount;
            }
          }
          return utils.calculate.NumberView({
            cellData: number,
            precision: 0,
          });
        },
        // cellRenderer: <TextWithTags precision={0} />,
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} type={2}>
              <div>均价</div>
              <div>(元/平米,个)</div>
            </HeaderRenderer>
          </div>
        ),
      });
    }
    // 金额
    if (_.includes(attributesCheckeds, 'price')) {
      fixedColumns.push({
        key: `${item.key}sumValue11`,
        dataKey: `${item.key}sumValue11`,
        title: '',
        align: 'right',
        width: 200,
        dataGetter: ({ rowData }) => {
          if (!rowData[item.key] || _.isEmpty(rowData[item.key])) {
            return '';
          }
          const rowDataX = rowData[item.key];
          const number = [];
          if (
            rowData.orgType === 'org_project' ||
            rowData.orgType === 'org_stage' ||
            rowData.orgType === 'org_group'
          ) {
            if (_.isNumber(rowDataX.carPlateTotalPrice) && _.isNumber(rowDataX.roomTotalPrice)) {
              number.push(_.sum([(rowDataX.carPlateTotalPrice + rowDataX.roomTotalPrice) / 10000]));
            }

            if (_.isNumber(rowDataX.roomTotalPrice)) {
              number.push(rowDataX.roomTotalPrice / 10000);
            }
            if (_.isNumber(rowDataX.carPlateTotalPrice)) {
              number.push(_.sum([rowDataX.carPlateTotalPrice / 10000]));
            }
          } else if (
            (rowData.orgType === 'org_build' ||
              rowData.orgType === 'org_product' ||
              rowData.orgType === 'org_house_package') &&
            !rowDataX.isParking
          ) {
            number.push(_.sum([rowDataX.roomTotalPrice / 10000]));
          } else if (rowDataX.isParking) {
            number.push(_.sum([rowDataX.carPlateTotalPrice]) / 10000);
          }
          return utils.calculate.NumberView({
            cellData: number,
            precision: 0,
          });
        },
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} type={3}>
              <div>金额</div>
              <div>(万元：合计/房源/车位)</div>
            </HeaderRenderer>
          </div>
        ),
      });
    }
  };

  getFixedColumns = (titleTree, attributesCheckeds) => {
    const cloneTitle = _.cloneDeep(titleTree);
    const fixedColumns = [];
    _.each(cloneTitle, a => {
      if (a.key === 'id') {
        fixedColumns.push({
          key: 'name',
          dataKey: 'name',
          title: '',
          width: 260,
          frozen: 'left',
          dataGetter: ({ rowData }) => {
            const rowDataX = rowData;
            let text = rowDataX.orgName;
            if (rowDataX.orgType === 'org_stage') {
              text = `${rowDataX.orgName}(${rowDataX.versionName})`;
            }
            if (rowDataX.orgType === 'org_salingparking') {
              text = '可售车位';
            }
            if (rowDataX.orgType === 'org_sale_parking') {
              text = '已售车位';
            }
            if (rowDataX.orgType === 'org_not_sale_parking') {
              text = '已定价未售车位';
            }
            if (rowDataX.orgType === 'org_forsaleparking') {
              text = '未推售车位';
            }
            const result = {
              text,
            };
            result.textFirst = true;
            if (rowData.orgType === 'org_build') {
              //   console.log(rowData)
              if (`${rowData.isSupply}` === '0') {
                result.tags = [{ text: '未供', color: 'orange', border: true }];
              }
              if (`${rowData.isSupply}` === '1') {
                result.tags = [{ text: '已供', color: 'green' }];
              }
            }
            return result;
          },
          cellRenderer: <TextWithTags />,
        });
      }
      if (
        a.key === 'land_invest_price' ||
        a.key === 'land_hk_price' ||
        a.key === 'un_start_price'
      ) {
        this.publicFun(a, attributesCheckeds, fixedColumns);
      }
      if (a.children && a.children.length > 0) {
        _.each(a.children, b => {
          // 权益货值
          if (b.key === 'dynamic_right_price') {
            if (_.includes(attributesCheckeds, 'price')) {
              fixedColumns.push({
                key: `${b.key}rightPrice`,
                dataKey: `${b.key}rightPrice`,
                title: '',
                align: 'right',
                width: 100,
                headerRenderer: () => (
                  <div>
                    <div>金额</div>
                    <div>(万元)</div>
                  </div>
                ),
                dataGetter: ({ rowData }) => {
                  if (!rowData[b.key] || _.isEmpty(rowData[b.key])) {
                    return '';
                  }
                  const rowDataX = rowData[b.key];
                  const number = [];
                  number.push(_.sum([rowDataX.rightPrice / 10000]));
                  return utils.calculate.NumberView({
                    cellData: number,
                    precision: 0,
                  });
                },
              });
            }
          } else if (b.key === 'dynamic_un_send_price') {
            // 未推售车位货值
            if (_.includes(attributesCheckeds, 'num')) {
              fixedColumns.push({
                key: `${b.key}carPlateCountW`,
                dataKey: `${b.key}carPlateCountW`,
                title: '',
                align: 'right',
                width: 100,
                dataGetter: ({ rowData }) => {
                  if (!rowData[b.key] || _.isEmpty(rowData[b.key])) {
                    return '';
                  }
                  const rowDataX = rowData[b.key];
                  const number = [];
                  number.push(
                    _.sum([
                      rowDataX.carPlateCount || rowDataX.carPlateCount === 0
                        ? rowDataX.carPlateCount
                        : '',
                    ]),
                  );
                  return utils.calculate.NumberView({
                    cellData: number,
                    precision: 0,
                  });
                },
                headerRenderer: () => (
                  <div>
                    <div>车位数</div>
                    <div>(个数)</div>
                  </div>
                ),
              });
            }
            if (_.includes(attributesCheckeds, 'price')) {
              fixedColumns.push({
                key: `${b.key}carPlateTotalPriceW`,
                dataKey: `${b.key}carPlateTotalPriceW`,
                title: '',
                align: 'right',
                width: 100,
                dataGetter: ({ rowData }) => {
                  if (!rowData[b.key] || _.isEmpty(rowData[b.key])) {
                    return '';
                  }
                  const rowDataX = rowData[b.key];
                  const number = [];
                  number.push(
                    _.sum([
                      rowDataX.carPlateTotalPrice || rowDataX.carPlateTotalPrice === 0
                        ? rowDataX.carPlateTotalPrice / 10000
                        : '',
                    ]),
                  );
                  return utils.calculate.NumberView({
                    cellData: number,
                    precision: 0,
                  });
                },
                headerRenderer: () => (
                  <div>
                    <div>金额</div>
                    <div>(万元)</div>
                  </div>
                ),
              });
            }
          } else {
            this.publicFun(b, attributesCheckeds, fixedColumns);
          }
        });
      }
    });
    return fixedColumns;
  };

  // 获取截止时间
  getChangeTimeValue = date => {
    const self = this;
    self.getItems(this.props, date);
    self.setState({
      yearMonth: date,
    });
  };

  // 导出报表
  overAllValueExport = () => {
    const { match } = this.props;
    const { yearMonth } = this.state;
    const params = {
      endDate: yearMonth,
      orgId: match.params.project,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/report/priceReportExport?${exportQueryString}`);
  };

  render() {
    const { expandedRowKeys, tree } = this.props.items;
    const { titleTree, attributesCheckeds, attributes, emptyTitle, yearMonth } = this.state;
    const headerRenderer = utils.getHeaderRenderer(titleTree, 2);
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath {...this.props} />}
        tags={<CurrentStage {...this.props} />}
        extra={
          <>
            <span>截止年月:</span>
            &nbsp;&nbsp;
            <DatePicker.MonthPicker
              allowClear={false}
              format="YYYY-MM"
              style={{ marginRight: '5px' }}
              defaultValue={moment(yearMonth, 'YYYY-MM')}
              disabledDate={current => current && current > moment().endOf('day')}
              onChange={(date, dateString) => {
                this.getChangeTimeValue(moment(date).format('YYYY-MM'), dateString);
              }}
            />
            {!_.isEmpty(tree) && (
              <>
                <AuthorizedButton authority="goodsValue_overall_exportReport">
                  <Button
                    onClick={() => this.overAllValueExport()}
                    className="yellow-button"
                    style={{ marginRight: '5px' }}
                  >
                    导出报表
                  </Button>
                </AuthorizedButton>
                <AuthorizedButton authority="goodsValue_overall_versionComparison">
                  <Button
                    onClick={() => {
                      // 根据项目id 筛选出 项目名
                      const orgTree = this.props.orgStructure.data;
                      const projectId = this.props.match.params.project;
                      const projectName = _.filter(orgTree, x => x.orgdepid === projectId)[0];
                      if (projectId && projectName) {
                        router.push({
                          pathname: '/common/goodsPriceContrast',
                          query: {
                            projectName: escape(projectName.orgname),
                            projectId,
                          },
                        });
                      }
                    }}
                  >
                    版本对比
                  </Button>
                </AuthorizedButton>
              </>
            )}
          </>
        }
      >
        <Card className="page-header-card">
          {!_.isEmpty(tree) ? (
            <>
              <Row type="flex" align="middle" justify="space-between">
                <Col>
                  <span>显示：</span>
                  <Select size="small" defaultValue="newestAllDynamic">
                    <Select.Option key="newestAllDynamic">最新全盘动态</Select.Option>
                  </Select>
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <Checkbox.Group
                    onChange={this.onChangeAttributesCheckeds}
                    options={attributes}
                    defaultValue={attributesCheckeds}
                  />
                </Col>
              </Row>
              <BaseTable
                subtractHeight="160px"
                headerHeight={[30, 30, 60]}
                headerRenderer={headerRenderer}
                defaultExpandedRowKeys={expandedRowKeys}
                expandColumnKey="name"
                fixedColumns={this.getFixedColumns(titleTree, attributesCheckeds)}
                treeData={tree}
              />
            </>
          ) : (
            <PageEmpty emptyTitle={emptyTitle} />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}
